#include "cgetoffcar.h"
#include <QDataStream>
#include <QTcpSocket>
#include "protocol/GetOffCar.h"
#include "protocol/srvGetOffCarAns.h"

CGetOffCar::CGetOffCar(QObject *parent)
{
}

CGetOffCar::~CGetOffCar()
{
}

bool CGetOffCar::prepareReadData(QTcpSocket *pTcpSocket, protocal::BasePtc *basePtc)
{
    // just tell the client that the server has got the get_on_car message
    QDataStream in(pTcpSocket);

    // follow the criteria of srvGetOnCarAns.h
    if (   basePtc->source != protocal::SERVER\
        || basePtc->srv_command != protocal::SRV_GET_CLIENT_OFF_MESSAGE
        || basePtc->size != sizeof(protocal::SrvGetOffCarAns))
    {
        // TODO: check whether it is necessary to clear the contents of in or pTcpSocket.
        // make an experiment to verify it.
        return false;
    }

    return true;
}

void CGetOffCar::prepareWriteData(QByteArray *block, void *param)
{
    // we cannot discrete this definition to the outside of the block,
    // and pass the reference to the funtion, or it will cause some
    // unknown problems, such as wrong streams. Maybe it is a bug of QT.
    QDataStream out(block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_3);

    protocal::GetOffCar* pGetOffCarParam = (protocal::GetOffCar*)param;

    // output the head information
    out << (qint32)(pGetOffCarParam->source) \
        << (qint32)(pGetOffCarParam->cli_command) \
        << (qint32)(pGetOffCarParam->size);

    char * temp = new char [10];
    memcpy(temp, pGetOffCarParam->orderid, 10);
    out << temp;
    delete[] temp;

    // send the current position
    out << pGetOffCarParam->gps.lat << pGetOffCarParam->gps.lon << pGetOffCarParam->gps.time;

    // send current time
    out << pGetOffCarParam->hour << pGetOffCarParam->minute << pGetOffCarParam->second;

    // send current date
    out << pGetOffCarParam->year << pGetOffCarParam->month << pGetOffCarParam->day;
}

void CGetOffCar::formResult()
{
    // do nothing for no extra data will be received
}
